package postgres

import (
	"context"
	"quipus/internal/database/model"
	apb "quipus/proto/gen/assist"

	_ "github.com/jackc/pgx/v5/stdlib"
	_ "github.com/joho/godotenv/autoload"
	"github.com/pkg/errors"
)

func (p *PGDB) CreateWorkflow(ctx context.Context, create *model.Workflow) error {
	p.query()
	qdo := q.WithContext(ctx)
	err := qdo.Workflow.Create(create)
	if err != nil {
		return errors.Wrap(err, "failed to create workflow")
	}
	return nil
}

func (p *PGDB) DeleteWorkflow(ctx context.Context, id int32) error {
	p.query()
	qdo := q.WithContext(ctx)
	_, err := qdo.Workflow.Where(q.Workflow.ID.Eq(id)).Delete()

	if err != nil {
		return err
	}

	return nil
}

func (p *PGDB) ListWorkflows(ctx context.Context, find *apb.FindWorkflow) ([]*model.Workflow, int32, error) {
	p.query()
	qdo := q.WithContext(ctx)
	workflow := qdo.Workflow
	if find.Id > 0 {
		workflow = workflow.Where(q.Workflow.ID.Eq(find.Id))
	}

	if find.Name != "" {
		workflow = workflow.Where(q.Workflow.Name.Eq(find.Name))
	}

	if find.TenantId > 0 {
		workflow = workflow.Where(q.Workflow.TenantID.Eq(find.TenantId))
	}

	if find.Pos != "" {
		workflow = workflow.Where(q.Workflow.Pos.Eq(find.Pos))
	}

	flows, count, err := workflow.FindByPage(int(find.Offset), int(find.Limit))
	if err != nil {
		return nil, 0, err
	}
	return flows, int32(count), nil
}

func (p *PGDB) GetWorkflow(ctx context.Context, find *apb.FindWorkflow) (*model.Workflow, error) {
	p.query()
	qdo := q.WithContext(ctx)
	workflow := qdo.Workflow
	if find.Id > 0 {
		workflow = workflow.Where(q.Workflow.ID.Eq(find.Id))
	} else {
		workflow = workflow.Where(q.Workflow.Name.Eq(find.Name)).Where(q.Workflow.TenantID.Eq(find.TenantId))
	}
	return workflow.First()
}

func (p *PGDB) CreateWorkflowRelation(ctx context.Context, create *model.WorkflowRelation) error {
	p.query()
	qdo := q.WithContext(ctx)
	err := qdo.WorkflowRelation.Create(create)
	if err != nil {
		return errors.Wrap(err, "failed to create workflow")
	}
	return nil
}

func (p *PGDB) ListWorkflowRelation(ctx context.Context, find *apb.WorkflowRelation) ([]*model.WorkflowRelation, error) {
	p.query()
	qdo := q.WithContext(ctx)
	relation := qdo.WorkflowRelation
	if find.FlowId > 0 {
		relation = relation.Where(q.WorkflowRelation.FlowID.Eq(find.FlowId))
	}
	if find.NextFlowId > 0 {
		relation = relation.Where(q.WorkflowRelation.NextFlowID.Eq(find.NextFlowId))
	}
	return relation.Find()
}

func (p *PGDB) DeleteWorkflowRelaton(ctx context.Context, delete *apb.WorkflowRelation) error {
	p.query()
	qdo := q.WithContext(ctx)
	relation := qdo.WorkflowRelation
	if delete.FlowId > 0 {
		relation = relation.Where(q.WorkflowRelation.FlowID.Eq(delete.FlowId))
	}
	if delete.NextFlowId > 0 {
		relation = relation.Where(q.WorkflowRelation.NextFlowID.Eq(delete.NextFlowId))
	}
	_, err := relation.Delete()
	return err
}
